﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Microsoft.Win32;
using System.Security.Cryptography;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace ISAMonitor.RESTTool
{
    public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
    {
        public TrustAllCertificatePolicy()
        { }

        public bool CheckValidationResult(ServicePoint sp,
         X509Certificate cert, WebRequest req, int problem)
        {
            return true;
        }
    }


    /// <summary>
    /// REST方式指令工具
    /// </summary>
    public class RESTCommand
    {
        /// <summary>
        /// 发送指令
        /// </summary>
        /// <param name="URL">所在URL</param>
        /// <param name="postinfo">指令信息</param>
        /// <returns>返回的JSON结果</returns>
        public static string SendCommand(string URL, string postinfo)
        {
            return htmlGetter(URL, postinfo, "UTF-8", true, null, null);
        }
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        { // Always accept

            return true; //总是接受
        } 




        public static string htmlGetter(string URL, string post, string codename, bool isPost, string[] headinfo, string Referer)
        {

            Encoding myEncoding = Encoding.GetEncoding(codename);

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
            //ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);





            request.ServicePoint.Expect100Continue = false;
            byte[] byteData = myEncoding.GetBytes(post);
            if (isPost)
            {
                request.Method = "POST";
            }
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteData.Length;
            //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            request.UserAgent = "RingDDNS/0.5 (wei.jacob@gmail.com)";

            if (Referer != null)
            {
                request.Referer = Referer;
            }

            if (headinfo != null)
            {
                for (int i = 0; i < headinfo.Length; i++)
                {
                    request.Headers.Add(headinfo[i]);
                }
            }

            //if (_isDebug)
            //{
            //    WebProxy myproxy = new WebProxy("127.0.0.1", 8888);
            //    request.Proxy = myproxy;
            //}

            if (isPost)
            {
               
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(byteData, 0, byteData.Length);
                }
            }
            
            try
            {
                //处理响应  
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader sr2 = new StreamReader(response.GetResponseStream(), myEncoding))
                    {
                        string rhtml = sr2.ReadToEnd();
                        return rhtml;
                    }
                }
            }
            catch (WebException ex)
            {
                throw;
            }
        }
    }

    public class RegistryHelper
    {
        public static string ValueName = "Ring 动态域名客户端（DNSPOD）";
        public static void SetStartUP(string filepath)
        {
            try
            {
                RegistryKey keyRun = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                keyRun.SetValue(ValueName, filepath);
            }
            catch
            { }
        }
        public static void DeleteStartUP()
        {
            RegistryKey keyRun = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
            keyRun.DeleteValue(ValueName);
        }
        public static bool CanStartUP()
        {
            return Registry.LocalMachine.GetValue(@"Software\Microsoft\Windows\CurrentVersion\Run\" + ValueName, -1) != (object)-1;
        }
        public static string GetUsername()
        {
            RegistryKey mykey = Registry.LocalMachine.OpenSubKey(@"Software\瑞盈通");
            return  mykey.GetValue("ringddns_username" ).ToString();
        
        }
        public static string GetPass()
        {
            RegistryKey mykey = Registry.LocalMachine.OpenSubKey(@"Software\瑞盈通");
            return Decode(mykey.GetValue("ringddns_password").ToString());


        }
        public static void SavePassword(string username, string password)
        {

            RegistryKey keyuser = Registry.LocalMachine.CreateSubKey(@"Software\瑞盈通");
            keyuser.SetValue("ringddns_username", username);
            keyuser.SetValue("ringddns_password", Encode( password));

        
        }

          const string KEY_64 = "VavicApp";//注意了，是8个字符，64位
          const string IV_64 = "VavicApp"; 

        public static string Encode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

                  DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
                  MemoryStream ms = new MemoryStream();
                  CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

                  StreamWriter sw = new StreamWriter(cst);
                  sw.Write(data);
                  sw.Flush();
                  cst.FlushFinalBlock();
                  sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

              }

        public static  string Decode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            byte[] byEnc;
            try
            {
                      byEnc = Convert.FromBase64String(data);
                  }
            catch
            {
                return null;
                  }

                  DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
                  MemoryStream ms = new MemoryStream(byEnc);
                  CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
                  StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
              }

    }
}

    